package com.aiyige.page.publish.coursedescription;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.page.my.settings.ConfigUltis;
import com.aiyige.page.publish.coursedescription.model.CourseDescriptionModel;
import com.aiyige.page.publish.majorcourse.model.MajorCourseFormModel;
import com.aiyige.page.publish.traingcard.model.TraingCardFormModel;
import com.aiyige.page.publish.traingclass.model.TraingClassFormModel;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.richtexteditor.RichTextEditor;
import com.aiyige.richtexteditor.model.RTEModel;
import com.aiyige.utils.DialogUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.dialog.LoadingDialog;
import com.aiyige.utils.widget.CommonBottomDialogFragment;
import com.aiyige.utils.widget.GprsNotificationDialogUtil;
import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.vondear.rxtools.RxNetTool;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

@Route(path = ARouterConfig.CourseDescriptionPage)
public class CourseDescriptionPage extends AppCompatActivity {
    public static final int REQUEST_CODE_PUBLISH = 0x1223;
    public static final String EXTRA_KEY_FORM_MODEL = "com.aiyige.extra.EXTRA_KEY_FORM_MODEL";
    @BindView(R.id.titleBackBtn)
    ImageView titleBackBtn;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.titleActionBtn)
    Button titleActionBtn;
    CommonBottomDialogFragment courseDescOptionDialog;
    CommonBottomDialogFragment courseDescEditOptionDialog;
    @Autowired
    MajorCourseFormModel majorCourseFormModel = null;
    @Autowired
    TraingClassFormModel traingClassFormModel = null;
    @Autowired
    TraingCardFormModel traingCardFormModel = null;
    CourseDescriptionModel courseDescriptionModel;
    @BindView(R.id.editor)
    RichTextEditor editor;

    @Override
    protected void onResume() {
        editor.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        editor.onPause();
        super.onPause();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_course_description);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        titleTv.setText(R.string.course_introduce);
        editor.onCreate(this);
        titleActionBtn.setText(R.string.next);
        if (majorCourseFormModel == null && traingClassFormModel == null && traingCardFormModel == null) {
            ToastX.show(R.string.unknown_error);
            finish();
            return;
        } else if (majorCourseFormModel != null) {
            courseDescriptionModel = majorCourseFormModel.getCourseDescriptionModel();
        } else if (traingClassFormModel != null) {
            courseDescriptionModel = traingClassFormModel.getCourseDescriptionModel();
        } else if (traingCardFormModel != null) {
            courseDescriptionModel = traingCardFormModel.getCourseDescriptionModel();
        }
        initDialog();
        restoreData();
        editor.setCallback(new RichTextEditor.Callback() {
            @Override
            public void notifyContentEmpty(boolean empty) {
                courseDescriptionModel.getRteModel().setEmpty(empty);
            }

            @Override
            public void contentReceived(RTEModel model) {
                if (isFinishing()) return;
                courseDescriptionModel.setRteModel(model);
                new CheckSensitiveWordTask(majorCourseFormModel, traingClassFormModel, traingCardFormModel).execute();
            }
        });
        editor.loadEditor();
    }

    @Override
    protected void onDestroy() {
        editor.onPause();
        super.onDestroy();
    }

    public void restoreData() {
        editor.setData(courseDescriptionModel.getRteModel());
    }

    public boolean checkFormValidate(boolean mute) {
        return true;
    }


    public void initDialog() {
        courseDescOptionDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.course_desc_option_dialog)
                .viewIdList(R.id.previewBtn, R.id.publishBtn, R.id.saveBtn, R.id.cancelBtn)
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.previewBtn: {

                                break;
                            }
                            case R.id.publishBtn: {
                                Postcard postcard = null;
                                if (majorCourseFormModel != null) {
                                    final int publishOperationType;
                                    switch (majorCourseFormModel.getOperationType()) {
                                        case PublishUtil.OPERATION_TYPE_COPY:
                                            publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_COPY_SUBMIT_REIVEW;
                                            break;
                                        case PublishUtil.OPERATION_TYPE_EDIT:
                                            publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_EDIT_SUBMIT_REIVEW;
                                            break;
                                        default:
                                            publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_SUBMIT_REVIEW;
                                            break;
                                    }
                                    if (!RxNetTool.isWifi(CourseDescriptionPage.this) && ConfigUltis.isEnableGprsNotification()) {
                                        GprsNotificationDialogUtil.createPublishBuilder(CourseDescriptionPage.this)
                                                .setPositiveButton(R.string.publish, new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        new PublishMajorCourseTask().execute(publishOperationType, majorCourseFormModel);
                                                    }
                                                })
                                                .setNegativeButton(R.string.cancel, null)
                                                .create()
                                                .show();
                                    } else {
                                        new PublishMajorCourseTask().execute(publishOperationType, majorCourseFormModel);
                                    }
                                } else if (traingClassFormModel != null) {
                                    postcard = ARouter.getInstance()
                                            .build(ARouterConfig.SelectGuaranteePage)
                                            .withString("subject", Moment.SUBJECT_TRAINING_COURSE)
                                            .withParcelable("traingClassFormModel", traingClassFormModel);
                                } else if (traingCardFormModel != null) {
                                    postcard = ARouter.getInstance()
                                            .build(ARouterConfig.SelectGuaranteePage)
                                            .withString("subject", Moment.SUBJECT_TRAINING_CARD)
                                            .withParcelable("traingCardFormModel", traingCardFormModel);
                                }
                                if (postcard != null) {
                                    final Postcard finalPostcard = postcard;
                                    if (!RxNetTool.isWifi(CourseDescriptionPage.this) && ConfigUltis.isEnableGprsNotification()) {
                                        GprsNotificationDialogUtil.createPublishBuilder(CourseDescriptionPage.this)
                                                .setPositiveButton(R.string.publish, new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        finalPostcard.navigation(CourseDescriptionPage.this, REQUEST_CODE_PUBLISH);
                                                    }
                                                })
                                                .setNegativeButton(R.string.cancel, null)
                                                .create()
                                                .show();
                                    } else {
                                        finalPostcard.navigation(CourseDescriptionPage.this, REQUEST_CODE_PUBLISH);
                                    }
                                }
                                break;
                            }
                            case R.id.saveBtn: {
                                if (majorCourseFormModel != null) {
                                    final int publishOperationType;
                                    switch (majorCourseFormModel.getOperationType()) {
                                        case PublishUtil.OPERATION_TYPE_COPY:
                                            publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_COPY_SAVE;
                                            break;
                                        case PublishUtil.OPERATION_TYPE_EDIT:
                                            publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_EDIT_SAVE;
                                            break;
                                        default:
                                            publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_SAVE;
                                            break;
                                    }
                                    if (!RxNetTool.isWifi(CourseDescriptionPage.this) && ConfigUltis.isEnableGprsNotification()) {
                                        GprsNotificationDialogUtil.createPublishBuilder(CourseDescriptionPage.this)
                                                .setPositiveButton(R.string.publish, new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        new PublishMajorCourseTask().execute(publishOperationType, majorCourseFormModel);
                                                    }
                                                })
                                                .setNegativeButton(R.string.cancel, null)
                                                .create()
                                                .show();
                                    } else {
                                        new PublishMajorCourseTask().execute(publishOperationType, majorCourseFormModel);
                                    }
                                } else if (traingClassFormModel != null) {
                                    final int publishOperationType;
                                    switch (traingClassFormModel.getOperationType()) {
                                        case PublishUtil.OPERATION_TYPE_COPY:
                                            publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_COPY_SAVE;
                                            break;
                                        case PublishUtil.OPERATION_TYPE_EDIT:
                                            publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_EDIT_SAVE;
                                            break;
                                        default:
                                            publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_SAVE;
                                            break;
                                    }

                                    if (!RxNetTool.isWifi(CourseDescriptionPage.this) && ConfigUltis.isEnableGprsNotification()) {
                                        GprsNotificationDialogUtil.createPublishBuilder(CourseDescriptionPage.this)
                                                .setPositiveButton(R.string.publish, new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        new PublishTraingClassTask().execute(publishOperationType, traingClassFormModel);
                                                    }
                                                })
                                                .setNegativeButton(R.string.cancel, null)
                                                .create()
                                                .show();
                                    } else {
                                        new PublishTraingClassTask().execute(publishOperationType, traingClassFormModel);
                                    }
                                } else if (traingCardFormModel != null) {
                                    final int publishOperationType;
                                    switch (traingCardFormModel.getOperationType()) {
                                        case PublishUtil.OPERATION_TYPE_COPY:
                                            publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_COPY_SAVE;
                                            break;
                                        case PublishUtil.OPERATION_TYPE_EDIT:
                                            publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_EDIT_SAVE;
                                            break;
                                        default:
                                            publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_SAVE;
                                            break;
                                    }
                                    if (!RxNetTool.isWifi(CourseDescriptionPage.this) && ConfigUltis.isEnableGprsNotification()) {
                                        GprsNotificationDialogUtil.createPublishBuilder(CourseDescriptionPage.this)
                                                .setPositiveButton(R.string.publish, new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        new PublishTraingCardTask().execute(publishOperationType, traingCardFormModel);
                                                    }
                                                })
                                                .setNegativeButton(R.string.cancel, null)
                                                .create()
                                                .show();
                                    } else {
                                        new PublishTraingCardTask().execute(publishOperationType, traingCardFormModel);
                                    }
                                }
                                break;
                            }
                        }
                    }
                })
                .build();

        courseDescEditOptionDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.course_desc_edit_option_dialog)
                .viewIdList(R.id.previewBtn, R.id.publishBtn, R.id.cancelBtn)
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.previewBtn: {

                                break;
                            }
                            case R.id.publishBtn: {
                                Postcard postcard = null;
                                if (majorCourseFormModel != null) {
                                    postcard = ARouter.getInstance()
                                            .build(ARouterConfig.SelectGuaranteePage)
                                            .withString("subject", Moment.SUBJECT_MAJOR_COURSE)
                                            .withParcelable("majorCourseFormModel", majorCourseFormModel);
                                } else if (traingClassFormModel != null) {
                                    postcard = ARouter.getInstance()
                                            .build(ARouterConfig.SelectGuaranteePage)
                                            .withString("subject", Moment.SUBJECT_TRAINING_COURSE)
                                            .withParcelable("traingClassFormModel", traingClassFormModel);
                                } else if (traingCardFormModel != null) {
                                    postcard = ARouter.getInstance()
                                            .build(ARouterConfig.SelectGuaranteePage)
                                            .withString("subject", Moment.SUBJECT_TRAINING_CARD)
                                            .withParcelable("traingCardFormModel", traingCardFormModel);
                                }
                                if (postcard != null) {
                                    final Postcard finalPostcard = postcard;
                                    if (!RxNetTool.isWifi(CourseDescriptionPage.this) && ConfigUltis.isEnableGprsNotification()) {
                                        GprsNotificationDialogUtil.createPublishBuilder(CourseDescriptionPage.this)
                                                .setPositiveButton(R.string.publish, new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        finalPostcard.navigation(CourseDescriptionPage.this, REQUEST_CODE_PUBLISH);
                                                    }
                                                })
                                                .setNegativeButton(R.string.cancel, null)
                                                .create()
                                                .show();
                                    } else {
                                        finalPostcard.navigation(CourseDescriptionPage.this, REQUEST_CODE_PUBLISH);
                                    }
                                }
                                break;
                            }
                        }
                    }
                })
                .build();

    }

    @Override
    public void onBackPressed() {
        DialogUtil.makeConfirmExitDialog(this, R.string.confirm_exit_edit, R.string.confirm, R.string.cancel).show();
    }

    @OnClick({R.id.titleBackBtn, R.id.titleActionBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleBackBtn:
//                Intent data = new Intent();
//                if (majorCourseFormModel != null) {
//                    data.putExtra(EXTRA_KEY_FORM_MODEL, majorCourseFormModel);
//                } else if (traingClassFormModel != null) {
//                    data.putExtra(EXTRA_KEY_FORM_MODEL, traingClassFormModel);
//                } else if (traingCardFormModel != null) {
//                    data.putExtra(EXTRA_KEY_FORM_MODEL, traingCardFormModel);
//                }
//                setResult(RESULT_CANCELED, data);
                DialogUtil.makeConfirmExitDialog(this, R.string.confirm_exit_edit, R.string.confirm, R.string.cancel).show();
                break;
            case R.id.titleActionBtn:
                if (checkFormValidate(false)) {
                    editor.requestContent();
                }
                break;
        }
    }

    public void showNextDialog() {
        int operationType = PublishUtil.OPERATION_TYPE_CREATE;
        if (majorCourseFormModel != null) {
            operationType = majorCourseFormModel.getOperationType();
        } else if (traingClassFormModel != null) {
            operationType = traingClassFormModel.getOperationType();
        } else if (traingCardFormModel != null) {
            operationType = traingCardFormModel.getOperationType();
        }
        switch (operationType) {
            case PublishUtil.OPERATION_TYPE_COPY:
            case PublishUtil.OPERATION_TYPE_CREATE:
                courseDescOptionDialog.show(getSupportFragmentManager(), "");
                break;
            default:
                courseDescEditOptionDialog.show(getSupportFragmentManager(), "");
                break;
        }
    }

    public class CheckSensitiveWordTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        MajorCourseFormModel majorCourseFormModel = null;
        TraingClassFormModel traingClassFormModel = null;
        TraingCardFormModel traingCardFormModel = null;

        public CheckSensitiveWordTask(MajorCourseFormModel majorCourseFormModel, TraingClassFormModel traingClassFormModel, TraingCardFormModel traingCardFormModel) {
            this.majorCourseFormModel = majorCourseFormModel;
            this.traingClassFormModel = traingClassFormModel;
            this.traingCardFormModel = traingCardFormModel;
        }

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(CourseDescriptionPage.this)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Moment moment = new Moment();
                if (majorCourseFormModel != null) {
                    moment = PublishUtil.convertMajorCourseFormModelToMoment(majorCourseFormModel);
                } else if (traingClassFormModel != null) {
                } else if (traingCardFormModel != null) {
                }


                Response<ResponseBody> response = ApiManager.getService().checkSensitiveWord(moment).execute();
                if (response.code() != ResponseCode.CREATED) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o == null) {
                showNextDialog();
            } else if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case RichTextEditor.REQUEST_CODE_INSERT_IMAGE:
            case RichTextEditor.REQUEST_CODE_INSERT_VIDEO:
                editor.onActivityResult(requestCode, resultCode, data);
                break;
            case REQUEST_CODE_PUBLISH:
                if (resultCode == RESULT_OK) {
                    setResult(RESULT_OK, data);
                    finish();
                }
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }

    public class PublishMajorCourseTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        int publishOperationType;
        MajorCourseFormModel majorCourseFormModel;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(CourseDescriptionPage.this)
                    .message(R.string.text_process)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            publishOperationType = (int) objects[0];
            majorCourseFormModel = (MajorCourseFormModel) objects[1];
            try {
                return PublishUtil.publishMajorCourse(publishOperationType, majorCourseFormModel);
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                setResult(RESULT_OK);
                finish();
                switch (publishOperationType) {
                    case PublishUtil.PUBLISH_OPERATION_TYPE_SAVE:
                    case PublishUtil.PUBLISH_OPERATION_TYPE_EDIT_SAVE:
                    case PublishUtil.PUBLISH_OPERATION_TYPE_COPY_SAVE:
                        ToastX.show(R.string.saving_course);
                        break;

                    case PublishUtil.PUBLISH_OPERATION_TYPE_SUBMIT_REVIEW:
                    case PublishUtil.PUBLISH_OPERATION_TYPE_EDIT_SUBMIT_REIVEW:
                    case PublishUtil.PUBLISH_OPERATION_TYPE_COPY_SUBMIT_REIVEW:
                        ToastX.show(R.string.publishing_course);
                        break;
                }
                PublishUtil.jumpToMMPage(CourseDescriptionPage.this);
            }

        }
    }

    public class PublishTraingClassTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        int publishOperationType;
        TraingClassFormModel traingClassFormModel;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(CourseDescriptionPage.this)
                    .message(R.string.text_process)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            publishOperationType = (int) objects[0];
            traingClassFormModel = (TraingClassFormModel) objects[1];
            try {
                return PublishUtil.publishTraingClass(publishOperationType, traingClassFormModel);
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                setResult(RESULT_OK);
                finish();
                PublishUtil.jumpToMMPage(CourseDescriptionPage.this);
            }

        }
    }

    public class PublishTraingCardTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        int publishOperationType;
        TraingCardFormModel traingCardFormModel;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(CourseDescriptionPage.this)
                    .message(R.string.text_process)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            publishOperationType = (int) objects[0];
            traingCardFormModel = (TraingCardFormModel) objects[1];
            try {
                return PublishUtil.publishTraingCard(publishOperationType, traingCardFormModel);
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                setResult(RESULT_OK);
                finish();
                PublishUtil.jumpToMMPage(CourseDescriptionPage.this);
            }
        }
    }
}
